package group.rober.jeki.controller

import group.rober.auth.AuthConsts
import group.rober.auth.entity.User
import group.rober.auth.service.AuthService
import group.rober.saber.kit.MapKit
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.UsernamePasswordToken
import org.apache.shiro.subject.Subject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.servlet.ModelAndView

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Controller
class LogonAndOffController {
    @Autowired
    private AuthService authService;

    @RequestMapping(path="/logon-action",method = RequestMethod.POST)
    public ModelAndView logonAction(@RequestParam("userCode") String userCode, @RequestParam("password") String password, HttpServletRequest request,HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userCode,password);
        //登录，登录成功后，把用户放到会话对象中去
        subject.login(token);
//        request.getSession().invalidate();
//        try{
//            subject.login(token);
//        }catch(UnknownAccountException e){
//            response.setStatus(HttpStatus.UNAUTHORIZED.value());
//        }catch(IncorrectCredentialsException e){
//            response.setStatus(HttpStatus.UNAUTHORIZED.value());
//        }

//        User user = authService.getUserByCode(userCode);
//        subject.getSession().setAttribute(AuthConsts.SESSION_USER,user);

        return new ModelAndView("redirect:/");
    }
    @RequestMapping(path="/logoff-action",method = RequestMethod.GET)
    public ModelAndView logoffAction(){
        Subject subject = SecurityUtils.getSubject();
        if(subject!=null)subject.logout();
        return new ModelAndView("redirect:/");
    }
}
